package com.xu.tools.config;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xu.tools.model.Result;
import com.xu.tools.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author xuguan
 * @date 2023/1/28
 * @desc 网关统一鉴权
 */
@EnableConfigurationProperties(AuthWhiteListProperties.class)
@Configuration
@Slf4j
public class GatewayGlobalAuthFilter implements GlobalFilter, Ordered {

    @Autowired
    AuthWhiteListProperties whiteListProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        // 校验是否命中白名单规则
        String path = request.getPath().toString();
        AntPathMatcher pathMatcher = new AntPathMatcher();
        for (String whitePattern : whiteListProperties.getWhites()) {
            if (pathMatcher.match(whitePattern, path)) {
                log.info("请求命中了白名单规则, 白名单路径正则whitePattern:{}, 请求路径path:{}", whitePattern, path);
                return chain.filter(exchange);
            }
        }

        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        log.info("token获取成功, {}", token);
        if (StringUtils.isEmpty(token)) {
            return buildMonoResponse(exchange, Result.fail(HttpStatus.UNAUTHORIZED, "无token信息, 请重新登录"));
        }

        try {
            // 解析token, 拿到userId
            String userKey = JwtUtil.getStrValue(token, "userKey");
            log.info("token解析成功, userKey:{}", userKey);
            request.mutate().header("userKey", userKey);
        } catch (JWTVerificationException e) {
            return buildMonoResponse(exchange, Result.fail(HttpStatus.UNAUTHORIZED, "token非法"));
        }

        return chain.filter(exchange);
    }

    private Mono<Void> buildMonoResponse(ServerWebExchange exchange, Result<?> result) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.getHeaders().add(HttpHeaders.CONTENT_ENCODING, StandardCharsets.UTF_8.name());

        DataBuffer databuffer = null;
        try {
            databuffer = response.bufferFactory()
                    .wrap(objectMapper()
                            .writeValueAsBytes(result));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        return response.writeWith(Mono.just(databuffer));
    }

    @Override
    public int getOrder() {
        return -1;
    }

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }
}
